from django.shortcuts import render, get_object_or_404
from .models import Book
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from datetime import timedelta
from .models import Author
from .forms import AuthorForm
from django.contrib.admin.views.decorators import staff_member_required
from .forms import BookForm
from django.shortcuts import redirect
from .forms import ReviewForm
from .models import Review




def index(request):
    # 获取当前会话中的访问次数，默认为0
    visit_count = request.session.get('visit_count', 0)
    # 访问次数加1
    visit_count += 1
    # 保存回会话
    request.session['visit_count'] = visit_count

    books = Book.objects.all()
    return render(request, 'books/index.html', {
        'books': books,
        'visit_count': visit_count,
    })


def detail(request, book_id):
    book = get_object_or_404(Book, pk=book_id)
    reviews = book.reviews.order_by('-created_at')
    review_form = None

    if request.user.is_authenticated:
        if request.method == 'POST' and 'review_submit' in request.POST:
            review_form = ReviewForm(request.POST)
            if review_form.is_valid():
                Review.objects.create(
                    user=request.user,
                    book=book,
                    content=review_form.cleaned_data['content']
                )
                return redirect('detail', book_id=book.id)
        else:
            review_form = ReviewForm()

    return render(request, 'books/detail.html', {
        'book': book,
        'reviews': reviews,
        'review_form': review_form,
    })
    book = get_object_or_404(Book, pk=book_id)
    if request.method == 'POST':
        if 'borrow' in request.POST and request.user.is_authenticated and not book.borrowed_by:
            book.borrowed_by = request.user
            book.borrowed_date = timezone.now().date()
            book.due_date = timezone.now().date() + timedelta(days=14)
            book.save()
        elif 'renew' in request.POST and request.user.is_authenticated and book.borrowed_by == request.user:
            book.renew(days=14)
    return render(request, 'books/detail.html', {'book': book})
@login_required
def mybooks(request):
    books = Book.objects.filter(borrowed_by=request.user)
    return render(request, 'books/mybooks.html', {'books': books})
def author_create(request):
    if request.method == 'POST':
        form = AuthorForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('author_list')
    else:
        form = AuthorForm()
    return render(request, 'books/author_form.html', {'form': form})

def author_update(request, author_id):
    author = get_object_or_404(Author, pk=author_id)
    if request.method == 'POST':
        form = AuthorForm(request.POST, instance=author)
        if form.is_valid():
            form.save()
            return redirect('author_list')
    else:
        form = AuthorForm(instance=author)
    return render(request, 'books/author_form.html', {'form': form})

def author_delete(request, author_id):
    author = get_object_or_404(Author, pk=author_id)
    if request.method == 'POST':
        author.delete()
        return redirect('author_list')
    return render(request, 'books/author_confirm_delete.html', {'author': author})

def author_list(request):
    authors = Author.objects.all()
    return render(request, 'books/author_list.html', {'authors': authors})
def author_detail(request, author_id):
    author = get_object_or_404(Author, pk=author_id)
    return render(request, 'books/author_detail.html', {'author': author})
@staff_member_required
def librarian_borrowed_books(request):
    borrowed_books = Book.objects.exclude(borrowed_by__isnull=True)
    return render(request, 'books/librarian_borrowed_books.html', {'borrowed_books': borrowed_books})
def book_create(request):
    if request.method == 'POST':
        form = BookForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = BookForm()
    return render(request, 'books/book_form.html', {'form': form})

def book_update(request, book_id):
    book = get_object_or_404(Book, pk=book_id)
    if request.method == 'POST':
        form = BookForm(request.POST, instance=book)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = BookForm(instance=book)
    return render(request, 'books/book_form.html', {'form': form})

def book_delete(request, book_id):
    book = get_object_or_404(Book, pk=book_id)
    if request.method == 'POST':
        book.delete()
        return redirect('index')
    return render(request, 'books/book_confirm_delete.html', {'book': book})